package com.topgay.service;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.topgay.dao.ChattingDAO;
import com.topgay.domain.ChattingMessage;

@Service
public class ChattingServiceImple implements ChattingService{
	@Autowired
	private ChattingDAO dao;
	
	public int makeTimeLineSeq(String fromId, String toId){
		String timeLineName = compareId(fromId, toId);
		return dao.createTimeLineSeq(timeLineName);
	}
	
	public ChattingMessage sendPicture(ChattingMessage message, MultipartFile picture) throws IllegalStateException, IOException{
		String basicDir = "C:\\Program Files\\Apache Software Foundation\\Tomcat 8.0\\webapps\\TopGay\\picture\\";
		String imgSrc = "/TopGay/picture/";
		String saveDir = "";
		String fileName = "";
		File dir;
		message.setTimeLineName(compareId(message.getFromId(), message.getToId()));
		
		if(picture != null && !picture.isEmpty()){
			saveDir = basicDir+message.getTimeLineName();
			imgSrc += message.getTimeLineName();
			fileName = picture.getOriginalFilename();
			message.setPicturePath(imgSrc+"/"+fileName);
			dir = new File(saveDir);
			dir.mkdirs();
			picture.transferTo(new File(saveDir, fileName));
		}
		
		return dao.selectMessageByNum(dao.insertMessageToChatting(message));
	}
	
	public ChattingMessage sendMessage(ChattingMessage message){
		message.setTimeLineName(compareId(message.getFromId(), message.getToId()));
		
		return dao.selectMessageByNum(dao.insertMessageToChatting(message));
	}
	
	public List<ChattingMessage> selectChattingMessageById(String fromId, String toId){
		String timeLineName = compareId(fromId, toId);
		List<ChattingMessage> list = dao.selectChattingMessageById(timeLineName, fromId);
		
		for(ChattingMessage tmp : list){
			dao.insertMessageToTimeLine(tmp);
		}
		
		return list;
	}
	
	public List<ChattingMessage> selectTimeLineMessageById(String fromId, String toId){
		String timeLineName = compareId(fromId, toId);
		return dao.selectTimeLineMessageById(timeLineName);
	}
	
	public ChattingMessage selectMessageByNum(int rowNum){
		return dao.selectMessageByNum(rowNum);
	}
	
	public String compareId(String id1, String id2){
		String biggerStr="";
		String shortStr = "";
		int ascii1=0, ascii2=0;
		
		if(id1.length() > id2.length()){
			shortStr = id2;
		}else{
			shortStr = id1;
		}
		
		for(int i = 0; i < shortStr.length(); i++){
			
						
			if(id1.charAt(i) != id2.charAt(i)){
				ascii1 = id1.charAt(i);
				ascii2 = id2.charAt(i);
				if(ascii1 > ascii2){
					biggerStr = id1+"_"+id2;
					break;
				}else{
					biggerStr = id2+"_"+id1;
					break;
				}
			}
		}
		
		return biggerStr;
	}
}
